package jui.maps
{
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	
	import jui.business.ManagersFactory;
	import jui.business.XMPPManager;
	import jui.maps.events.ConnectEvent;
	import jui.maps.events.RosterEvent;
 	
	public class SendEventMap extends EventDispatcher implements IJUIEventMap 
	{
		private var app: JUI;
		private var xmppManager: XMPPManager;
		
		public function setManagers(): void
		{
			var gm: Function = ManagersFactory.getInstance().getManager;
			xmppManager = gm( XMPPManager.getQName() );
		}
		
		/**
		 * Event Handler for user click on 'Send' Button or Hit Ctrl+Enter
		 */
		public function setHandlers(): void
		{
			app.systemManager.addEventListener(RosterEvent.ROSTER_ITEM_SELECTED, rosterItemSelectedHandler);
			app.systemManager.addEventListener(ConnectEvent.CONNECT_AS_USER, connectAsUserHandler);
			app.systemManager.addEventListener(ConnectEvent.DISCONNECT_USER, disconnectUser);
			app.systemManager.addEventListener(ConnectEvent.BREAK_IT, breakIt);
		}
		
		//----------------------------------------------------------------------
		// Event Handlers go gere
		//----------------------------------------------------------------------
		
		private function rosterItemSelectedHandler(event:RosterEvent): void
		{
			xmppManager.setRespondentUser(event.jUserVO);
		}
		
		private function connectAsUserHandler(event:ConnectEvent): void
		{
			xmppManager.connectAsUser(event.jUserVO);
		}
		
		private function disconnectUser(event:ConnectEvent): void
		{
			xmppManager.disconnect();
		}

		private function breakIt(event:ConnectEvent):void 
		{
			// send invalid XML, useful for testing auto-reconnect from stream error
			xmppManager.breakIt();
		}
		
		public function SendEventMap(target:IEventDispatcher=null, app: JUI=null): void
 		{
			if(instance) throw new Error("SendEventMap is singleton");
			this.app = app;
			setManagers();
			setHandlers();
 		}
		
		public static var instance: SendEventMap;
	}
}